package cn.hy.dataSync.statistics.container.communicator;


import cn.hy.dataSync.config.JobConfig;
import cn.hy.dataSync.config.TaskConfig;
import cn.hy.dataSync.job.State;
import cn.hy.dataSync.statistics.VMInfo;
import cn.hy.dataSync.statistics.communication.Communication;
import cn.hy.dataSync.statistics.container.collector.AbstractCollector;
import cn.hy.dataSync.statistics.container.report.AbstractReporter;

import java.util.List;
import java.util.Map;

/**
 * 容器，管理整个 job 和 task 的统计信息
 */
public abstract class AbstractContainerCommunicator {

    /**
     * 默认每5分钟打印一次
     */
    private static final long DEFAULT_REPORT_INTERVAL = 300000;

    private JobConfig jobConfig;
    private AbstractCollector collector;
    private AbstractReporter reporter;

    private String jobId;

    private VMInfo vmInfo = VMInfo.getVmInfo();
    private long lastReportTime = System.currentTimeMillis();

    public JobConfig getJobConfig() {
        return this.jobConfig;
    }

    public AbstractCollector getCollector() {
        return collector;
    }

    public AbstractReporter getReporter() {
        return reporter;
    }

    public void setCollector(AbstractCollector collector) {
        this.collector = collector;
    }

    public void setReporter(AbstractReporter reporter) {
        this.reporter = reporter;
    }

    public String getJobId() {
        return jobId;
    }

    public AbstractContainerCommunicator(JobConfig jobConfig) {
        this.jobConfig = jobConfig;
        this.jobId = jobConfig.getJobId();
    }

    /**
     * 注册状态汇报器
     *
     * @param taskConfigs 任务配置
     */
    public abstract void registerCommunication(List<TaskConfig> taskConfigs);

    /**
     * 获取汇报器，获取此次job中 所有 task 的统计信息
     *
     * @return 汇报器
     */
    public abstract Communication collect();

    /**
     * 状态汇报
     *
     * @param communication 汇报器
     */
    public abstract void report(Communication communication);

    /**
     * 搜集状态
     *
     * @return 当前状态
     */
    public abstract State collectState();

    /**
     * 按任务ID获取汇报器
     *
     * @param id 任务ID
     * @return 汇报器
     */
    public abstract Communication getCommunication(Integer id);

    /**
     * 获取所有汇报器
     *
     * @return 回报器 MAP
     */
    public abstract Map<Integer, Communication> getCommunicationMap();

    public void resetCommunication(Integer id) {
        Map<Integer, Communication> map = getCommunicationMap();
        map.put(id, new Communication());
    }

    /**
     *  5分钟打印一次 vm 的信息
     */
    public void reportVmInfo() {
        long now = System.currentTimeMillis();
        if (now - lastReportTime >= DEFAULT_REPORT_INTERVAL) {
            //当前仅打印
            if (vmInfo != null) {
                vmInfo.getDelta(true);
            }
            lastReportTime = now;
        }
    }
}